package com.winston.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * created by winston on 2024/4/3
 */
public class JdkProxy {
    interface MessageSvc{
        void send(String msg);
    }

    static class SmsMessageSvc implements MessageSvc{
        @Override
        public void send(String msg) {
            System.out.println(SmsMessageSvc.class.getName() + ": " + msg);
        }
    }

    // 定义动态代理类
    static class MessageInvocationHandler implements InvocationHandler {
        private Object object;

        public MessageInvocationHandler(Object object) {
            this.object = object;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("before");
            Object invoke = method.invoke(object, args);
            System.out.println("after");
            return invoke;
        }
    }

    public static void main(String[] args) {
        SmsMessageSvc smsMessageSvc = new SmsMessageSvc();
        MessageSvc proxyInstance = (MessageSvc) Proxy.newProxyInstance(smsMessageSvc.getClass().getClassLoader(),
                                                                       smsMessageSvc.getClass().getInterfaces(),
                                                                       new MessageInvocationHandler(smsMessageSvc));
        proxyInstance.send("test msg");
    }
}

